package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //请求头中内容被拦截，后续直接使用方法取用
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //web-all收到的请求
        HttpServletRequest request = requestAttributes.getRequest();
        //web-all发出的请求
        if (request != null){
            //真实用户
            String userId = request.getHeader("userId");
            if (!StringUtils.isEmpty(userId)){
                requestTemplate.header("userId",userId);
            }
            //临时用户
            String userTempId = request.getHeader("userTempId");
            if (!StringUtils.isEmpty(userTempId)){
                requestTemplate.header("userTempId",userTempId);
            }
        }
    }
}
